namespace LightBox.Flickr.Providers
{
	using System;
	using System.Collections.Specialized;
	using System.Configuration.Provider;
	using System.IO;
	using System.Web.Configuration;

	using LightBox.Providers;
	using LightBox.Hosting;

	using FlickrNet;

	/// <summary>
	/// 
	/// </summary>
	public class FlickrImageProvider : ImageProvider, IImageUrlHandler
	{
		private Flickr flckrAccess;

		/// <summary>
		/// Public default constructor
		/// </summary>
		public FlickrImageProvider() { }

		#region Initialization & Configuration

		/// <summary>
		/// 
		/// </summary>
		/// <param name="name"></param>
		/// <param name="config"></param>
		public override void Initialize(string name, NameValueCollection config)
		{
			base.Initialize(name, config);
			string connString = GetConnectionString(config);
		}

		private string GetConnectionString(NameValueCollection config)
		{
			// Initialize _connectionString
			string connect = config["connectionStringName"];

			if (String.IsNullOrEmpty(connect))
			{
				throw new ProviderException
					("Empty or missing connectionStringName");
			}

			config.Remove("connectionStringName");

			if (WebConfigurationManager.ConnectionStrings[connect] == null)
			{
				throw new ProviderException("Missing connection string");
			}

			string connectionString = WebConfigurationManager.ConnectionStrings
				[connect].ConnectionString;

			if (String.IsNullOrEmpty(connectionString))
			{
				throw new ProviderException("Empty connection string");
			}

			return connectionString;
		}

		#endregion

		/// <summary>
		/// 
		/// </summary>
		/// <param name="info"></param>
		/// <returns></returns>
		public override Stream GetImageByUrl(string url)
		{
			Stream imgStream = null;
			
			if (flckrAccess != null)
			{
				imgStream = flckrAccess.DownloadPicture(url);
			}

			return imgStream;
		}

		#region IImageUrlHandler Members

		public string[] SupportedUrls
		{
			get { throw new Exception("The method or operation is not implemented."); }
		}

		public bool IsUrlSupported(string url)
		{
			throw new Exception("The method or operation is not implemented.");
		}

		#endregion
	}
}